import type { InternalAxiosRequestConfig } from "axios";
import { isFunction } from "../../helper/judge";

export default class AxiosCancel {
  private static pendingMap = new Map<string, AbortController>();

  static getPendingUrl(config: InternalAxiosRequestConfig) {
    return [config.method, config.url].join("&");
  }

  static addPending(config: InternalAxiosRequestConfig) {
    const controller = new AbortController();

    config.signal = controller.signal;


    let url = this.getPendingUrl(config);

    this.removePending(url);

    this.pendingMap.set(url, controller);
  }

  static removePending(url: string) {

    if (this.pendingMap.has(url)) {
      const c = this.pendingMap.get(url);

      c && isFunction(c) && c.abort();

      this.pendingMap.delete(url);
    }
  }

  static removeAll() {
    this.pendingMap.forEach((c) => {
      c && isFunction(c) && c.abort();
    });

    this.pendingMap.clear();
  }

  static reset() {
    this.pendingMap = new Map<string, AbortController>();
  }
}
